﻿using System.Web.Mvc;
using ProgrammingSchool.Infrastructure.Filters.Authorize;
using ProgrammingSchool.Models.Account;
using ProgrammingSchool.Core.Interfaces;
using ProgrammingSchool.DataContext;
using System.Web.Security;

namespace ProgrammingSchool.Controllers
{
    public class AccountController : BaseController
    {
        private readonly IUserService _userService;


        public AccountController(IUserService userService)
        {
            _userService = userService;
        }

        [AllowAnonymous]
        public ActionResult Index()
        {
            return View();
        }

        [AllowAnonymous]
        public ActionResult LogOn(string targetId)
        {
            return PartialView(new LogOnModel()
                {
                     TargetId = targetId
                });
        }

        [HttpPost]
        [AllowAnonymous]
        public ActionResult LogOn(LogOnModel model)
        {
            if (ModelState.IsValid)
            {
                var user = _userService.GetUser(model.Login, model.Password);
                if (user != null)
                {
                    FormsAuthentication.SetAuthCookie(user.Id.ToString(), model.RememberMe);
                    return PartialView("RedirectFromAjax", "/Home/Index");
                }
                else
                {
                    ModelState.AddModelError(string.Empty, "Incorrect login or password");
                }
            }
            return PartialView(model);
        }

        [HttpGet]
        [AllowAnonymous]
        public ActionResult Registration()
        {
            return PartialView();
        }

        [HttpPost]
        [AllowAnonymous]
        public ActionResult Registration(RegistrationModel model)
        {
            if (ModelState.IsValid)
            {
                var user = new T_User()
                               {
                                   Login = model.Email,
                                   Password = model.Password
                               };
                var res = _userService.CreateNewUser(user);
                if (res.State == Core.Models.StateEnum.Success)
                    return PartialView("RedirectFromAjax", "/Home/Index");
                else
                    //and show ErrorMessage
                    ModelState.AddModelError(string.Empty, res.ErrorMessage);
                    return PartialView(model);
            }

            return PartialView(model);
        }

    }
}
